package com.shiku.im.repository;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.shiku.im.comm.constants.KConstants;
import com.shiku.im.entity.ClientConfig;
import com.shiku.im.entity.Config;
import com.shiku.im.entity.PayConfig;
import com.shiku.redisson.AbstractRedisson;
import com.shiku.utils.StringUtil;
import org.redisson.api.RBucket;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Repository
public class CoreRedisRepository extends AbstractRedisson {

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public RedissonClient getRedissonClient() {
        return redissonClient;
    }


    public static final String GET_CONFIG = "app:config";
    public static final String GET_CLIENTCONFIG = "clientConfig";
    public static final String GET_PAYCONFIG = "payConfig";

    /**
     * 安卓的华为推送初始化access_token
     */
    public static final String HWPushAccessToken = "impush:hw:%s";


    public  void setConfig(Config config) {
        setBucket(GET_CONFIG, config.toString());
    }


    public  Config getConfig() {
        String config=getBucket(String.class,GET_CONFIG);
        return StringUtil.isEmpty(config) ? null : JSON.parseObject(config, Config.class);
    }
    public  ClientConfig getClientConfig() {
        String config=getBucket(String.class,GET_CLIENTCONFIG);
        return StringUtil.isEmpty(config) ? null : JSON.parseObject(config, ClientConfig.class);
    }

    public  void setClientConfig(ClientConfig clientConfig) {
         setBucket(GET_CLIENTCONFIG,JSON.toJSONString(clientConfig));
    }

    public void setPayConfig(PayConfig payConfig){
        setBucket(GET_PAYCONFIG,JSON.toJSONString(payConfig));
    }

    public PayConfig getPayConfig(){
        String config = getBucket(String.class,GET_PAYCONFIG);
        return StringUtil.isEmpty(config) ? null : JSON.parseObject(config,PayConfig.class);
    }

    /**
     * 全站公告
     */
    public static final String NOTICE_CONFIG = "notice:config";

    /**
     * 设置全站公告信息
     * @param jsonData 设置全站公告
     */
    public void saveNoticeConfig(String jsonData) {
        setBucket(NOTICE_CONFIG, jsonData);
    }

    /**
     * 获取全站公告信息
     **/
    public String getNoticeConfig(){
        RBucket<String> bucket = redissonClient.getBucket(NOTICE_CONFIG);
        return bucket.get();
    }

    /**
     * 每一次签到次数刷新时间大小，默认七天
     */
    public static String SIGN_MAX_COUNT_KEY = "sign_max_count";

    public void setSignMaxCount(Long maxCount) {
        redissonClient.getAtomicLong(SIGN_MAX_COUNT_KEY).set(maxCount);
    }

    public Long getSignMaxCount() {
        long maxCount = redissonClient.getAtomicLong(SIGN_MAX_COUNT_KEY).get();
        if (maxCount == 0) {
            return 7L;
        }
        return maxCount;
    }

    /**
     * 签到奖励策略，内容以 Map 存储，根据累计签到次数获取奖励金额，金额以分为单位
     */
    public static String SIGN_POLICY_AWARD_KEY = "sign_policy_award";

    public void setSignPolicyAward(Long day, Integer amount) {
        redissonClient.getMap(SIGN_POLICY_AWARD_KEY).put(day, amount);
    }

    public Integer getSignPolicyAward(Long day) {
        return (Integer) redissonClient.getMap(SIGN_POLICY_AWARD_KEY).get(day);
    }

    public Map<Long, Integer> getSignPolicyAward() {
        RMap<Long, Integer> map = redissonClient.getMap(SIGN_POLICY_AWARD_KEY);
        if (map.size() == 0) {
            Map<Long,Integer> tempMap=new HashMap<>();
            for (long i = 1; i <= getSignMaxCount(); i++) {
                tempMap.put(i, i % 2 == 0 ? 0 : 1);
            }
            redissonClient.getMap(SIGN_POLICY_AWARD_KEY).putAll(tempMap);
            tempMap.clear();
            return tempMap;
        }
        return map;
    }

    /**
     * 去掉redis定义有效期的随机数
     * 用严格保证数据有效期限 比如：华为推送的token有效期
     */
    public boolean setBucketImpl(String key, Object obj, long time, TimeUnit unit){
        RBucket<Object> bucket = getRedissonClient().getBucket(key);
        bucket.set(obj,time,unit);
        return true;
    }

    /**
     * 保存华为推送初始化的access_token
     * expireIn 单位秒
     */
    public void saveHWPushToken(String access_token){
        String key=String.format(HWPushAccessToken, "pushToken");
        setBucketImpl(key,access_token, KConstants.Expire.HOUR, TimeUnit.SECONDS);
    }

    /**
     * 获取华为推送access_token
     */
    public Map<String,String> getHWPushToken(){
        String key=String.format(HWPushAccessToken, "pushToken");
        RBucket<String> value = redissonClient.getBucket(key);
        if(StringUtil.isEmpty(value.get())){
            return Maps.newConcurrentMap();
        }
        Map tokenMaps = Maps.newConcurrentMap();
        tokenMaps.put("access_token",value.get());
        // 注 :remainTimeToLive同pttl命令单位毫秒，ttl命令单位秒
        tokenMaps.put("expireIn",value.remainTimeToLive());
        return tokenMaps;
    }
}
